package com.zx.shiro.utils;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

import org.apache.shiro.codec.Base64;
import org.apache.shiro.session.Session;

/**
 * 序列化工具类
 * @author 郑雪
 * @date 2021-11-23
 */
public class SerializableUtils {

	/**
	 * 将一个Shiro的Session对象序列化为一个字符串
	 * @param session
	 * @return
	 */
	public static String serialize(Session session) {
		try {
			ByteArrayOutputStream bos = new ByteArrayOutputStream();
			ObjectOutputStream oos = new ObjectOutputStream(bos);
			oos.writeObject(session);
			return Base64.encodeToString(bos.toByteArray());
		} catch (Exception e) {
			throw new RuntimeException("序列化Shiro的Session对象失败");
		}
	}

	/**
	 * 反序列化，将一个session字符串反序列化为一个Session对象
	 * @param sessionStr
	 * @return
	 */
	public static Session deserialize(String sessionStr){
		try {
			ByteArrayInputStream bis = new ByteArrayInputStream(
					Base64.decode(sessionStr));
			ObjectInputStream ois = new ObjectInputStream(bis);
			return (Session)ois.readObject();
		} catch (Exception e) {
			throw new RuntimeException("反序列化Shiro的Session对象失败");
		}
	}
}
